<?php

namespace app\webapi\vms\service;

use app\webapi\common\BaseService;
use app\webapi\vms\model\TemplateCategoryModel;
use app\webapi\vms\model\TemplateModel;
use app\webapi\vms\model\WebsiteModel;
use library\OWException;
use think\facade\Request;

/**
 * @模板服务类
 */
class TemplateService extends BaseService
{
    /**
     * @desc 获取模板分类列表
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author zhaozhiwei
     * @time 2023/12/8-15:57
     */
    public function getCategoryList()
    {
        return TemplateCategoryModel::field(['id', 'name'])->select();
    }

    /**
     * @desc 获取模板分页列表
     * @param $params
     * @return array
     * @author zhaozhiwei
     * @time 2023/12/8-16:11
     */
    public function getPaginateList($page_no, $page_size, $category_id,$website_id)
    {
        //组装查询条件
        $where = [];
        if ($category_id != '' && $category_id != 0) $where['category_id'] = $category_id;

        //定义查询参数
        $fields = ['id', 'name', 'number', 'category_id', 'cover'];

        //查询分页数据
        $list = TemplateModel::field($fields)->where($where)->paginate(['page' => $page_no, 'list_rows' => $page_size]);

        //获取列表中分类id数组
        $category_id_arr = array_column($list->items(), 'category_id');
        //查询分类名称
        $category_names_kv_list = TemplateCategoryModel::where(['id' => $category_id_arr])->column('name', 'id');

        //组装数据
        foreach ($list->items() as &$v) {
            $v['category_name'] = $category_names_kv_list[$v['category_id']] ?? '';
            $v['preview_path_pc'] = Request::domain().'admin/SystemTemplate/index?template_id=1&type=pc';
            $v['preview_path_mobile'] = Request::domain().'admin/SystemTemplate/index?template_id=1&type=mobile';
        }
        unset($v);
        return $list;
    }

    /**
     * @desc 立即使用模板
     * @param $id
     * @param $website_id
     * @return true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author zhaozhiwei
     * @time 2023/12/18-9:38
     */
    public function immediateUse($id, $website_id)
    {
        //检测模板id是否存在
        $info = TemplateModel::where(['id' => $id])->find();
        if (empty($info)) {
            throw new OWException('模板id不存在');
        }

        $row = WebsiteModel::where(['id' => $website_id])->update(['template_id' => $id,'current_step'=>3]);
        if ($row < 1) {
            throw new OWException('设置失败');
        }
        return true;
    }
}